const DEFAULT_CACHE_TIME = 60 * 60 * 24 * 7;

export const createStorage = ({
  prefixKey = "",
  storage = localStorage,
  timeout = DEFAULT_CACHE_TIME,
}) => {
  const Storage = class {
    constructor() {
      this.storage = storage;
      this.prefixKey = prefixKey;
    }

    getKey(key) {
      return `${this.prefixKey}${key}`.toUpperCase();
    }

    /**
     *
     *  Set cache
     * @param {string} key
     * @param {*} value
     * @expire Expiration time in seconds
     * @memberof Cache
     */
    set(key, value, expire = timeout) {
      const stringData = JSON.stringify({
        value,
        time: Date.now(),
        expire: expire * 1000,
      });
      this.storage.setItem(this.getKey(key), stringData);
    }

    /**
     *Read cache
     * @param {string} key
     * @def {string} null)
     * @memberof Cache
     */
    get(key, def = null) {
      const val = this.storage.getItem(this.getKey(key));
      if (!val) return def;
      try {
        const data = JSON.parse(val);
        const { value, expire, time } = data;
        if (expire >= new Date().getTime() - time) {
          return value;
        }
        this.remove(key);
      } catch (e) {
        return def;
      }
    }

    /**
     *Read cache
     * @param {string} key
     * @memberof Cache
     */
    remove(key) {
      this.storage.removeItem(this.getKey(key));
    }

    clear() {
      this.storage.clear();
    }
  };

  return new Storage();
};

export const Storage = createStorage({});

export default Storage;
